import { useState, useCallback } from 'react';
import appBridge, { AppBridge } from '@/utils/app-bridge';

/**
 * Hook for using voice input functionality
 */
export const useVoiceInput = () => {
  const [text, setText] = useState<string>('');
  const [isListening, setIsListening] = useState<boolean>(false);
  const [error, setError] = useState<Error | null>(null);

  const startVoiceInput = useCallback(async (options: {
    maxDuration?: number;
    language?: string;
    prompt?: string;
  } = {}) => {
    if (!appBridge.isInApp()) {
      setError(new Error('Voice input is only available in the native app'));
      return;
    }

    try {
      setIsListening(true);
      setError(null);
      
      const recognizedText = await appBridge.startVoiceInput(options);
      setText(recognizedText);
      return recognizedText;
    } catch (err) {
      setError(err as Error);
      return '';
    } finally {
      setIsListening(false);
    }
  }, []);

  return {
    text,
    isListening,
    error,
    startVoiceInput,
    isAvailable: appBridge.isInApp()
  };
};

/**
 * Hook for using the voice assistant (小安)
 */
export const useVoiceAssistant = () => {
  const [isActive, setIsActive] = useState<boolean>(false);
  const [error, setError] = useState<Error | null>(null);

  const activateAssistant = useCallback(async (options: {
    query?: string;
    fullScreen?: boolean;
    theme?: 'light' | 'dark';
  } = {}) => {
    if (!appBridge.isInApp()) {
      setError(new Error('Voice assistant is only available in the native app'));
      return false;
    }

    try {
      setIsActive(true);
      setError(null);
      
      await appBridge.activateVoiceAssistant(options);
      return true;
    } catch (err) {
      setError(err as Error);
      return false;
    } finally {
      // The assistant might still be active even after this function returns
      // The native app will handle closing the assistant UI
    }
  }, []);

  return {
    isActive,
    error,
    activateAssistant,
    isAvailable: appBridge.isInApp()
  };
};
